//
//  StoreNearbyViewController.m
//  Custom_Weibo
//
//  Created by LEO on 12/19/15.
//  Copyright © 2015 Leo_Lei. All rights reserved.
//

#import "StoreNearbyViewController.h"
#import "PositionModel.h"

@interface StoreNearbyViewController ()<CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource> {
    CLLocationManager *_locationManager;
    UITableView *_tableView;
    NSMutableArray *_dataArray;
//    MKMapView *_mapView;
}

@end

@implementation StoreNearbyViewController

#pragma mark - SYSTEM_METHODS
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Store Nearby";
    
    //  1)Get current location.
    [self getLocation];
    
    //  2)Show nearby interest position.
    [self showNearbyInterest];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - LOCATION_GET
- (void)getLocation {
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        if (DEVICE_AVALIABLE_IOS8) {
            /*  Ask the device for permission,when using the application, it
             will request for location visit.
             You can also set it as 'requestAlwaysAuthorization', then
             application will continuously updating location,even if you aren't
             using the application.
             */
            [_locationManager requestWhenInUseAuthorization];
        }
    }
    //  Set the accuracy of locating for current location.
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    
    _locationManager.delegate = self;
    
    //  Begin updating location.
    [_locationManager startUpdatingLocation];
}

#pragma mark SHOW_INTEREST
- (void)showNearbyInterest {
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kLocationCellID];
    
    [self.view addSubview:_tableView];
}

#pragma mark - UITABLEVIEW_DELEGATE_AND_DATASOURCE
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kLocationCellID
                                                            forIndexPath:indexPath];
    
    PositionModel *model = _dataArray[indexPath.row];
    cell.textLabel.text = model.title;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.icon]
                      placeholderImage:[UIImage imageNamed:@"icon"]];
    return cell;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    /*  If you don't wanna it coutinuously get your location, you can set it
     updating action just for once.
     */
    [_locationManager stopUpdatingLocation];
    
    //  We only need the latest location, so we get the last object for location.
    CLLocation *location = [locations lastObject];
    
    NSString *longitude = [NSString stringWithFormat:@"%lf", location.coordinate.longitude];
    NSString *latitude = [NSString stringWithFormat:@"%lf", location.coordinate.latitude];
    
    //  Get location through network.
    [self loadNearByPositionWithLongitude:longitude latitude:latitude];
    
}

- (void)loadNearByPositionWithLongitude:(NSString *)longitude latitude:(NSString *)latitude {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:longitude forKey:@"long"];
    [params setObject:latitude forKey:@"lat"];
    [params setObject:@"50" forKey:@"count"];
    
    [NetworkService requestAFUrl:kNearby_Pois httpMethod:@"GET" params:params data:nil block:^(id result, NSURLResponse *response, NSError *error) {
        NSArray *position = [result objectForKey:@"pois"];
        NSMutableArray *positionArray = [[NSMutableArray alloc] init];
        for (NSDictionary *dic in position) {
            PositionModel *model = [[PositionModel alloc] initWithDataDic:dic];
            [positionArray addObject:model];
            _dataArray = positionArray;
            [_tableView reloadData];
        }
    }];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
